package net.orange.framework.controller;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import net.orange.architecture.process.ProcessFactory;
import net.orange.architecture.web.Web;
import net.orange.framework.logic.IMenuProcess;
import net.orange.framework.logic.IUserProcess;
import net.orange.framework.model.Menu;
import net.orange.framework.model.User;

/**
 * The user log in page managed bean using in JSF MVC modal. it is include the
 * web page content and control the action and page forward direction in the web
 * site.
 */
@ManagedBean(name = "userlogin")
@SessionScoped
public class UserLoginController {
	/**
	 * The login account
	 */
	private String login_no;

	/**
	 * The login password.
	 */
	private String login_pwd;

	/**
	 * @return Returns the login_no.
	 */
	public String getLogin_no() {
		return login_no;
	}

	/**
	 * @param login_no
	 *            The login_no to set.
	 */
	public void setLogin_no(String login_no) {
		this.login_no = login_no;
	}

	/**
	 * @return Returns the login_pwd.
	 */
	public String getLogin_pwd() {
		return login_pwd;
	}

	/**
	 * @param login_pwd
	 *            The login_pwd to set.
	 */
	public void setLogin_pwd(String login_pwd) {
		this.login_pwd = login_pwd;
	}

	/**
	 * Validate the user's login no and password.
	 * 
	 * @return The JSF tag return ("success" for success,"fail" for fail.)
	 * @throws Exception
	 */
	public String login() throws Exception {
		IUserProcess process = (IUserProcess) ProcessFactory.get(User.class);

		if (login_no == null || login_no.length() <= 0 || login_pwd == null
				|| login_pwd.length() <= 0) {
			Web.setMessage(null, "* Please input the user account and password");
			return Web.JSF_USER_LOGIN_FAIL;
		}

		boolean b = process.validate(login_no, login_pwd);

		if (!b) {
			Web.setMessage(null, "Invalid Username and/or Password!");
		} else {
			User currentUser = (User) process.find("login_no", login_no);
			IMenuProcess menuProcess = (IMenuProcess) ProcessFactory
					.get(Menu.class);
			// Set the current user to session.
			Web.getSession().setAttribute(Web.JSF_USER_CURRENT, currentUser);
			// Set the current user's menu to session.
			Web.getSession().setAttribute(Web.JSF_USER_CURRENT_MENUS,
					menuProcess.get(currentUser));
		}

		return (b ? Web.JSF_USER_LOGIN_SUCCESS : Web.JSF_USER_LOGIN_FAIL);
	}

	/**
	 * Log out
	 * 
	 * @return The JSF tag "logout".
	 * @throws Exception
	 */
	public String logout() throws Exception {
		return Web.JSF_USER_LOGOUT;
	}
}
